<?php
/**
 * Created by PhpStorm.
 * User: JX
 * Date: 2017/8/21
 * Time: 10:26
 */

namespace App\Http\Controllers\API\WeChat;


use App\Http\Controllers\Controller;
use App\Models\WeChat;
use App\Models\WechatUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class WeChatUsersController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();
        if($user->hasRole('singer')){
            $wechatlist = DB::table('user_wechats')->where(['user_id'=>$user->id])->pluck('wechat_id')->toArray();
        }else{
            $wechatlist = WeChat::query()->pluck('id');
        }
        $queryString = $request->get('query', '');
        $models = WechatUser::with('wechat')
            ->where('nick_name', 'like', '%' . $queryString . '%')
            ->whereIn('w_id', $wechatlist)
            ->orderBy('id','desc')
            ->paginate(10);
        return $models;
    }
    /**
     * 添加公众号
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
       // var_dump(1);die;
        $model = new WechatUser();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(WechatUser $WechatUser, Request $request)
    {
        $WechatUser->fill($request->all());
        if ($WechatUser->save()) {
            return $WechatUser;
        } else {
            return response($WechatUser->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        return $this->findModel($id);
    }




    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = WechatUser::findOrFail($id);
        return $model;
    }
}